<template>
  <slide-view
    v-empty="!canShowDetail"
    :listener-ids="listenerIDs"
    :no-listener-ids="noListenerIDs"
    :no-listener-class="noListenerClass"
    :body-style="{padding: 0, height: '100%'}"
    xs-empty-icon="nopermission"
    :xs-empty-text="$t('crm.contract.49f2600be55262455d1c72733920fa97')"
    @afterEnter="viewAfterEnter"
    @close="hideView">
    <div ref="crmDetailMain" v-loading="loading" class="detail-main no-padding">
      <flexbox
        v-if="canShowDetail && detailData"
        direction="column"
        align="stretch"
        class="d-container">
        <wk-detail-header
          :subtitle="$t('crm.contract.91e338ee640d58b2d0d40f3c3de2c755')"
          :class="{'is-shadow': bodyIsScroll}"
          :title="detailData.name"
          :page-list="pageList"
          :dropdowns="handleOperations"
          @command="headerRightClick"
          @pageChange="pageChange">
          <template slot="left">
            <span v-if="detailData.checkStatus == 8" class="is-invalid">{{ $t('crm.contract.2d852b74afc3db4e277990667aac5477') }}</span>
            <span v-if="detailData.checkStatus == 13" class="is-invalid">（已终止）</span>
            <span v-if="detailData.checkStatus == 14" class="is-invalid">（已归档）</span>
            <el-tooltip :content="detailData.star == 0 ? '添加关注' : '取消关注'" effect="dark" placement="top">
              <i
                v-if="detailData.star == 0"
                class="el-icon-star-off focus-icon"
                @click="toggleStar()" />
              <i
                v-else
                class="wk wk-focus-on focus-icon active"
                @click="toggleStar()" />
            </el-tooltip>
          </template>

          <template slot="right">
            <time-piece v-if="showTimer && isCall" />
            <el-button
              v-if="userInfo.loginType != 3"
              class="wk-premium-info-btn"
              data-type="Signature">
              <i class="wk wk-icon-lightning-solid wk-premium-info-icon" data-type="Signature" />
              <span class="wk-premium-info-label" data-type="Signature">{{ $t('crm.contract.b84d4af669fdcd4caa4e81c1ac1a0284') }}</span>
            </el-button>
            <el-button
              v-if="showTransfer"
              class="head-handle-button"
              @click="headerRightClick('transfer')">
              {{ $t('crm.contract.639167a8bf616b6e0bffdc3f2a2b5dfc') }}
            </el-button>
            <el-button
              v-if="showEdit"
              class="head-handle-button"
              type="primary"
              @click="headerRightClick('edit')">
              {{ $t('crm.contract.77bdd152c86f9ec7aef1efae616f0d95') }}
            </el-button>
          </template>
        </wk-detail-header>

        <!-- 标签 -->
        <flexbox v-if="tagInfo" wrap="wrap" class="wk-tags-content">
          <tag-view :value="tagInfo.value" :max-length="Infinity" wrap="wrap">
            <wk-tag
              v-model="tagInfo.value"
              :disabled="tagInfo.disabled"
              :placeholder="tagInfo.placeholder"
              :data="tagInfo"
              :options="tagInfo.setting"
              @change="tagChange($event)">
              <el-tooltip
                slot="reference"
                :content="$t('crm.contract.962a48168e66e56eea468f70c44b6cac')"
                effect="dark"
                placement="top">
                <el-button
                  type="icon"
                  size="small"
                  icon="wk wk-icon-label-solid" />
              </el-tooltip>
            </wk-tag>
          </tag-view>
        </flexbox>

        <!-- 快捷创建 -->
        <wk-quick-create-bar
          :list="activityHandle"
          @command="quickCreateClick" />

        <div class="d-container-body" @scroll="bodyScroll">
          <detail-head-base :list="headDetails" />
          <relative-stage-records
            :id="id"
            :crm-type="crmType"
            :is-stage-flow="true"
            :detail="detailData"
            @handle="detailHeadHandle" />
          <flexbox
            class="left-right-wrap"
            :class="{'is-hidden-right': !detailData.examineRecordId }"
            align="stretch">
            <div class="left">
              <el-tabs v-model="tabCurrentName" nav-mode="more">
                <el-tab-pane
                  v-for="(item, index) in tabNames"
                  :key="index"
                  :label="item.label"
                  :name="item.name"
                  lazy>
                  <template slot="label">
                    <el-badge
                      :value="item.num"
                      :hidden="item.num <= 0"
                      type="primary">
                      {{ item.label }}
                    </el-badge>
                  </template>
                  <component
                    :is="item.name"
                    :id="id"
                    :ref="item.name"
                    :detail="detailData"
                    :type-list="logTyps"
                    :crm-type="crmType"
                    @handle="detailHeadHandle" />
                </el-tab-pane>
              </el-tabs>
            </div>
            <div class="right">
              <examine-info-section
                v-if="detailData.examineRecordId"
                :id="id"
                :record-id="detailData.examineRecordId"
                examine-type="crm_contract"
                @on-handle="examineHandle" />
            </div>
          </flexbox>
        </div>
      </flexbox>
    </div>

    <!-- 新建编辑 -->
    <c-r-m-all-create
      v-if="crmCreateShow"
      :action="createActionInfo"
      :crm-type="createCRMType"
      :examine-info="examineInfo"
      @save-success="editSaveSuccess"
      @close="crmCreateShow=false" />

    <!-- 任务创建 -->
    <task-create
      v-if="taskCreateShow"
      :action="taskCreateAction"
      @save="editSaveSuccess"
      @close="taskCreateShow = false" />

    <!-- 转移 -->
    <transfer-handle
      v-if="transferDialogShow"
      :props="transferHandleProps"
      :dialog-visible.sync="transferDialogShow"
      @handle="detailHeadHandle({type: 'transfer'})" />

    <!-- 团队添加 -->
    <teams-handle
      v-if="teamsDialogShow"
      :dialog-visible.sync="teamsDialogShow"
      :props="teamsHandleProps"
      @handle="detailHeadHandle({type: 'team'})" />
  </slide-view>
</template>

<script>
import {
  crmContractReadAPI,
  crmContractDeleteAPI,
  crmContractCancelAPI
} from '@/api/crm/contract'

import SlideView from '@/components/SlideView'
import TransferHandle from '@/components/Page/SelectionHandle/TransferHandle' // 转移
import Stage from '../components/Stage' // 阶段记录
import RelativeStageRecords from '../components/RelativeStageRecords' // 阶段记录
import Activity from '../components/Activity' // 活动
import CRMEditBaseInfo from '../components/CRMEditBaseInfo' // 商机基本信息
import RelativeHandle from '../components/RelativeHandle' // 相关操作
import RelativeTeam from '../components/RelativeTeam' // 团队成员
import RelativeProduct from '../components/RelativeProduct' // 团队成员
import RelativeReturnMoney from '../components/RelativeReturnMoney' // 相关回款
import RelativeFiles from '../components/RelativeFiles' // 相关附件
import RelativeVisit from '../components/RelativeVisit' // 回访
import RelativeInvoice from '../components/RelativeInvoice' // 发票
import RelativePrint from '../components/RelativePrint' // 相关打印
import ExamineInfoSection from '@/components/Examine/ExamineInfoSection'
import RelativeAmountRatio from '../components/RelativeAmountRatio' // 金额比例设置

import CRMAllCreate from '../components/CRMAllCreate' // 新建页面
import TaskCreate from '@/views/oa/taskExamine/task/Create'

import DetailMixin from '../mixins/Detail'
import { separator } from '@/filters/vueNumeralFilter/filters'
import { getWkDateTime } from '@/utils'
import { mapGetters } from 'vuex'

export default {
  // 客户管理 的 合同详情
  name: 'ContractDetail',
  components: {
    SlideView,
    TransferHandle,
    Stage,
    RelativeStageRecords,
    Activity,
    CRMEditBaseInfo,
    RelativeHandle,
    RelativeTeam,
    RelativeProduct,
    RelativeReturnMoney,
    RelativeFiles,
    RelativeVisit,
    RelativeInvoice,
    RelativePrint,
    ExamineInfoSection,
    CRMAllCreate,
    TaskCreate,
    RelativeAmountRatio
  },
  mixins: [DetailMixin],
  props: {
    // 详情信息id
    id: [String, Number],
    // 监听的dom 进行隐藏详情
    listenerIDs: {
      type: Array,
      default: () => {
        return ['crm-main-container']
      }
    },
    // 不监听
    noListenerIDs: {
      type: Array,
      default: () => {
        return []
      }
    },
    noListenerClass: {
      type: Array,
      default: () => {
        return ['el-table__body']
      }
    }
  },
  data() {
    return {
      // 展示加载loading
      loading: false,
      crmType: 'contract',
      headDetails: [],
      tabCurrentName: 'CRMEditBaseInfo'
    }
  },
  computed: {
    ...mapGetters([
      'isWxUser'
    ]),
    // 活动操作
    activityHandle() {
      const temps = [
        {
          command: 'task',
          icon: 'wk wk-icon-task-line',
          label: this.$t('crm.contract.2406e351afae0ca7f4d8f59cb66dea5e'),
          auth: 'oa.taskExamine'
        }, {
          command: 'receivables',
          icon: 'wk wk-receivables-line',
          label: this.$t('crm.contract.1babb4571adcc1722380e56577800a2a'),
          auth: 'crm.receivables.save'
        },
        {
          command: 'team',
          icon: 'wk wk-icon-s-seas-line',
          label: '添加团队成员',
          auth: `crm.${this.crmType}.teamsave`
        }
      ]

      // if (this.canCreateFollowRecord) {
      //   temps = [{
      //     type: 'log',
      //     label: '写跟进'
      //   }].concat(temps)
      // }

      return temps.filter(item => {
        return !item.auth || this.$auth(item.auth)
      })
    },

    // 可操作选项
    handleOperations() {
      return this.getOperations(['print', 'delete', 'cancel', 'copyContract'])
    },

    // tabs
    tabNames() {
      var tempsTabs = []
      if (this.crm.contract && this.crm.contract.read) {
        tempsTabs.push({ label: this.$t('crm.contract.29ff4581572efd941a3b0452d61658c9'), name: 'CRMEditBaseInfo' })
      }

      tempsTabs.push({ label: this.$t('crm.contract.c3329cea10f0f5e536949edebfb33ff2'), name: 'Activity' })

      if (this.crm.product && this.crm.product.index && this.detailData?.relatedProduct) {
        tempsTabs.push({ label: this.$t('crm.contract.11d62731a89f4d33424398975ed6ab98'), num: this.tabsNumber.productCount, name: 'RelativeProduct' })
      }
      if ((this.crm.receivables && this.crm.receivables.index) || (this.crm.receivablesPlan && this.crm.receivablesPlan.index)) {
        tempsTabs.push({ label: this.$t('crm.contract.5d63933714c7c5733006d992fa8dfb12'), num: this.tabsNumber.receivablesCount, name: 'RelativeReturnMoney' })
      }
      if (this.crm.visit && this.crm.visit.index) {
        tempsTabs.push({ label: this.$t('crm.contract.75604df2d41fa33007c75a39072192e1'), num: this.tabsNumber.returnVisitCount, name: 'RelativeVisit' })
      }

      if (this.crm.invoice && this.crm.invoice.index) {
        tempsTabs.push({ label: this.$t('crm.contract.d7f9c855258fe7070e6cc0b03dcc4fcc'), num: this.tabsNumber.invoiceCount, name: 'RelativeInvoice' })
      }
      tempsTabs.push({ label: this.$t('crm.contract.1eb6092f9d61c1babb6850f5107f39f5'), num: this.tabsNumber.memberCount, name: 'RelativeTeam' })
      tempsTabs.push({ label: '金额比例设置', name: 'RelativeAmountRatio' })
      tempsTabs.push({ label: this.$t('crm.contract.80c98c6003d0703a13b37a9bda184fe9'), num: this.tabsNumber.fileCount, name: 'RelativeFiles' })
      if (this.userInfo.loginType != 3) {
        tempsTabs.push({ label: this.$t('crm.contract.ddef6c9b39832e2f5c3f42a4a0bbab4c'), name: 'RelativeHandle' })
      }
      if (this.crm.contract && this.crm.contract.print) {
        tempsTabs.push({ label: this.$t('crm.contract.b9ef92018ab8ef7507bbeb1fad33fdeb'), name: 'RelativePrint' })
      }
      // if (this.statusShow) {
      //   tempsTabs.unshift({ label: '阶段记录', name: 'RelativeStageRecords' })
      // }
      return tempsTabs
    },

    // 根据记录筛选
    logTyps() {
      return [{
        icon: 'all',
        color: '#2362FB',
        command: '',
        label: this.$t('crm.contract.64a3899d167181eeae3448b0de59fb11')
      }, {
        icon: 'contract',
        color: '#FD5B4A',
        command: 6,
        label: this.$t('crm.contract.c206f66ab7a89811b32a00c8ebdce3c0')
      }, {
        icon: 'o-task',
        color: '#D376FF',
        command: 11,
        label: this.$t('crm.contract.d62d2b9a0101512b14e5c9f5cebb20dd')
      }, {
        icon: 'receivables',
        color: '#FFB940',
        command: 7,
        label: this.$t('crm.contract.d4d2fee1b347d20045834a0e8c6cd415')
      }, {
        icon: 'log',
        color: '#5864FF',
        command: 8,
        label: this.$t('crm.contract.f82c1c99021f53fb064284176a50939a')
      }, {
        icon: 'approve',
        color: '#9376FF',
        command: 9,
        label: this.$t('crm.contract.0f66c8717b4ea59ad45f7e32972a616b')
      }]
    }
  },
  mounted() {
    if (this.crm.contract && this.crm.contract.read) {
      this.tabCurrentName = 'CRMEditBaseInfo'
    }
  },
  methods: {
    /**
     * 详情
     */
    getDetial() {
      this.loading = true
      crmContractReadAPI(this.id)
        .then(res => {
          this.loading = false
          // 创建回款计划的时候使用
          const resData = res.data || {}
          this.detailData = resData

          this.headDetails = [
            // { title: '合同编号', value: resData.num },
            { title: this.$t('crm.contract.7850c44448ebd93f1c15f91367091d75'), value: resData.customerName },
            { title: `合同金额（${this.crmMoneyUnit}）`, value: separator(this.crmMoney(resData.money || 0)) },
            { title: this.$t('crm.contract.6d22a54945a2362c688d9c16ec44b5c7'), value: getWkDateTime(resData.orderDate) },
            { title: `回款金额（${this.crmMoneyUnit}）`, value: separator(this.crmMoney(resData.receivablesMoney || 0)) },
            { title: this.$t('crm.contract.07e9d9151e027f2fe9176f457b2f059f'), value: resData.ownerUserName, formType: 'user' }
          ]
        })
        .catch(() => {
          this.loading = false
          this.hideView()
        })
    },

    /**
     * 关闭
     */
    hideView() {
      this.$emit('hide-view')
    },

    /* ------------------------ 头部事件 ------------------------ */
    /**
     * @description: 头部右侧点击事件
     * @param {*}
     * @return {*}
     */
    headerRightClick(type) {
      if (type === 'transfer') {
        this.transferDialogShow = true
      } else if (type === 'edit') {
        if (this.detailData.checkStatus === 1) {
          this.$message.error(this.$t('crm.contract.91ea0c15dbb6550b9557e157801533b2'))
          return false
        } else if (this.detailData.checkStatus === 3) {
          this.$message.error(this.$t('crm.contract.565c6540c8833b78c0c235119e622c69'))
          return false
        } else {
          this.createCRMType = this.crmType
          this.createActionInfo = {
            type: 'update',
            id: this.id,
            batchId: this.detailData.batchId
          }

          this.examineInfo = {
            examineStatus: this.detailData.checkStatus,
            recordId: this.detailData.examineRecordId
          }
          this.crmCreateShow = true
        }
      } else if (type == 'delete') {
        this.$confirm(
          this.$t('crm.contract.616d302afb799a6b101eee3a0bdf3de5'),
          this.$t('crm.contract.fad708d85d20dafee931efa659972d44'),
          {
            confirmButtonText: this.$t('crm.contract.3abbe98dc5b4bd02c35c20e20e86c420'),
            cancelButtonText: this.$t('crm.contract.083c23c8b1ade99ae01fd11e7f1fd5ed'),
            type: 'warning'
          }
        )
          .then(() => {
            crmContractDeleteAPI([this.id])
              .then(res => {
                this.$message({
                  type: 'success',
                  message: this.$t('crm.contract.22aa560a5ca207391d6b134eb3792113')
                })
                this.detailHeadHandle({ type })
              })
              .catch(() => {})
          })
          .catch(() => {})
      } else if (type == 'cancel') {
        let message = this.$t('crm.contract.e441f735a26c54de80329155ffc18901')
        if (this.detailData.receivablesCount) {
          message = this.$t('crm.contract.5565fdbe8d0efa06585173223d377ce7')
        }
        this.$confirm(message, this.$t('crm.contract.b2997a4658bd4b2956c02f0b30816098'), {
          confirmButtonText: this.$t('crm.contract.30cbffb0060cfdda287f266fa0686f70'),
          cancelButtonText: this.$t('crm.contract.b1bc5c663b98281ae354abeed12ef1b0'),
          type: 'warning'
        })
          .then(() => {
            crmContractCancelAPI({
              contractId: this.id
            })
              .then(res => {
                this.$message.success(this.$t('crm.contract.f61f177f0b0b37ab099313b3c8b18bbb'))
                this.detailHeadHandle({ type })
              })
              .catch(() => {})
          })
          .catch(() => {})
      } else if (type == 'print') {
        // 打印
        const id = this.detailData[`${this.crmType}Id`]
        const routeData = this.$router.resolve(`/print/?module=${this.crmType}&id=${id}`)
        window.open(routeData.href, '_blank')
      } else if (type == 'copyContract') {
        this.createCRMType = this.crmType
        this.createActionInfo = { type: 'update', title: this.$t('crm.contract.fee1cade5036bf216ef08868ebfb18fa'), id: this.id, isCopy: true }
        this.crmCreateShow = true
      }
    },

    /**
     * 审核操作
     */
    examineHandle(data) {
      this.detailHeadHandle({ type: 'examine' })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/crmdetail.scss";

.d-container-body {
  margin-top: 8px;
}

.is-invalid {
  color: $--color-text-placeholder;
}
</style>
